# _*_coding:utf-8_*_

import pymysql


class Mysql:
    def conndb(self):
        # 连接数据库函数
        conn = pymysql.connect(host='localhost', user='root', passwd='root', db='test', charset='utf8')
        cur = conn.cursor()
        return (conn, cur)

    def runsql(self, sql):
        # 执行命令
        lastid = 0
        try:
            # 创建连接
            conn, cursor = self.conndb()
            # 创建游标
            cursor = conn.cursor()
            # 执行SQL语句
            cursor.execute(sql)
            # 获取最后一条数据
            lastid = cursor.lastrowid
            # 关闭游标和连接
            cursor.close()
            conn.close()
        except Exception as e:
            print(e)
        return lastid

    def getdata(self, sql):
        # 查询数据
        datas = []
        try:
            # 创建连接
            conn, cursor = self.conndb()
            # 创建游标
            cursor = conn.cursor()
            # 执行SQL语句
            cursor.execute(sql)
            # 获取所有数据
            datas = cursor.fetchall()
            # 关闭游标和连接
            cursor.close()
            conn.close()
        except Exception as e:
            print(e)
        return datas


# 测试数据库连接
# mysql = Mysql()
# print(mysql.getdata("select * from `_3`"))
#